﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace ResistorMoudel
{
    public class HIOK2Resistor : Resistor
    {
        public Label lblShow;
        private Label lblState;
        private Button btStartTest;
        private Button btRead;
        private Button button1;
        private System.Windows.Forms.Button btSerialSet;

        public const int firstSleep = 300;
        public const int secondSleep = 1100;

        public override int TestMaxTime { get => 10000; }

        public override string HeartSendCmd { get => "*IDN?\r\n"; }

        public override string StartTestSendCmd => ":MEM:CLE;:START\r\n";

        public override string StopTestSendCmd => ":STOP\r\n";

        public override string ReadDataSendCmd => ":MEASure?\r\n";


        /// <summary>
        /// 判定结果查询
        /// </summary>
        private string comparatorCmd = ":MEASURE:COMPARATOR?\r\n";

        /// <summary>
        /// 测量值、判定结果查询
        /// </summary>
        private string resValCmd = ":MEASURE:RESULT?\r\n";
        /// <summary>
        /// 返回测试值的数量
        /// </summary>
        private string resCountCmd = ":MEM:COUN?\r\n";

        /// <summary>
        /// 所有的数据 命令
        /// </summary>
        public string memDatasCmd = ":MEM?\r\n";
        /// <summary>
        /// 开启存储功能
        /// </summary>
        private string memOnCmd = ":MEM:STAT ON\r\n";
        /// <summary>
        /// 清空缓存
        /// </summary>
        private string memClearCmd = ":MEM:CLE\r\n";

        /// <summary>
        /// 设置最小电阻量程
        /// </summary>
        private string rangeSetCmd = ":MOHM:RANGE 2M\r\n";
        /// <summary>
        /// 设置电阻量程为 AUTO
        /// </summary>
        private string rangeAutoSetCmd = ":MOHM:RANGE AUTO\r\n";


        public override string AskTimerCmd => "TIMER?\r\n";

        public override string AskVoltageCmd => "TESTV?\r\n";

        public override string AskLowCmd => "LOW?\r\n";

        public override string AskUppCmd => "UPP?\r\n";


        public void Init()
        {
            //Resistorserial.SendMessage(memOnCmd);//开启存储功能
            ////Thread.Sleep(500);
            ////Resistorserial.SendMessage(memClearCmd);//清空缓存
            //Thread.Sleep(500);
            //Resistorserial.SendMessage(rangeAutoSetCmd);//电阻量程 Auto
        }



        public HIOK2Resistor(string name, bool isFormShowType) : base(name, isFormShowType)
        {
            InitializeComponent();
            Name = name;
            Resistorserial.RtsEnable = true;
            ConnectionStatusChanged += HIOK2Resistor_ConnectionStatusChanged;
        }
        public HIOK2Resistor(string name) : this(name, true)
        {

        }

        bool firstLoad = true;
        private void HIOK2Resistor_ConnectionStatusChanged(object sender, EventArgs e)
        {
            if (firstLoad)
            {
                if ((bool)sender == true)
                {
                    Init();
                    firstLoad = false;
                    ConnectionStatusChanged -= HIOK2Resistor_ConnectionStatusChanged;
                }
            }
        }

        public HIOK2Resistor() : base()
        {
            InitializeComponent();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="values"></param>
        /// <returns>返回FALSE表示NG</returns>
        public bool IsOKorNG(float[] values)
        {
            for (int i = 0; i < values.Length - 1; i++)
            {
                if (values[i + 1] - values[i] < 0 && Math.Abs(values[i + 1] - values[i]) / values[i] > 0.5f && values[i + 1] < 2)
                {
                    return false;
                }
            }
            return true;
        }


        /// <summary>
        /// 判断过程曲线是否OK，false表示NG
        /// </summary>
        /// <param name="values"></param>
        /// <param name="index">当前NG位置的索引</param>
        /// <returns></returns>
        public bool IsOKorNG(float[] values, out int index)
        {
            index = 0;
            for (int i = 0; i < values.Length - 1; i++)
            {
                if (values[i + 1] - values[i] < 0 && Math.Abs(values[i + 1] - values[i]) / values[i] > 0.5f && values[i + 1] < 2)
                {
                    index = i + 1;
                    return false;
                }
            }
            return true;
        }
        public float[] GetContinueDatas(int testtimeSecond)
        {
            int numcout = testtimeSecond * 1000 / 40;
            return GetContinueDatas(testtimeSecond, numcout);
        }
        public float[] GetContinueDatas(int testtimeSecond,int maxDataCount)
        {
            Resistorserial.AllReceivedString = "";
            int timecount = 0;
            Thread.Sleep(firstSleep);
            Resistorserial.SendMessage(memDatasCmd);
            Thread.Sleep(secondSleep);
            float[] retfloats;
            while (true)
            {
                retfloats = getAllData();
                //250
                //int numcout = testtimeSecond * 1000 / 20;
                //200
                int numcout = maxDataCount;

                if (retfloats.Length < numcout)
                {
                    timecount++;
                    if (timecount > 100)
                    {
                        break;
                        //throw new Exception($"电阻测试仪获取连续数据解析异常。数据量不足{numcout},数据内容：" + Resistorserial.AllReceivedString);
                    }
                    Thread.Sleep(100);
                }
                else
                {
                    break;
                }
            }
            return retfloats;
        }

        private float[] getAllData()
        {
            List<float> retfloatlist = new List<float>();
            string allstring = Resistorserial.AllReceivedString;
            string[] ret = allstring.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            //if (ret.Length < 5)
            //{
            //    throw new Exception("电阻测试仪获取连续数据解析异常。解析内容为空。数据内容：" + allstring);
            //}
            for (int i = 0; i < ret.Length; i++)
            {
                if (ret[i].Contains("E+06"))
                {
                    string[] res = ret[i].Split(',').Where(s => s != "").ToArray();

                    for (int j = 0; j < res.Length; j++)
                    {
                        res[j] = res[j].Replace("E+06", "");

                        bool parseFlag = float.TryParse(res[j], out float retfloat);
                        if (parseFlag)
                            retfloatlist.Add(retfloat);
                    }
                }
                else
                {
                    continue;
                }
            }
            return retfloatlist.ToArray();
        }


        public override void BeginCtor(string name)
        {
            ConnectionStatusChanged += HIOKIResistor_ConnectionStatusChanged;
            base.BeginCtor(name);
        }

        public override void EndCtor(string name)
        {
            base.EndCtor(name);
        }

        private void HIOKIResistor_ConnectionStatusChanged(object sender, EventArgs e)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action(() =>
                {
                    HIOKIResistor_ConnectionStatusChanged(sender, e);
                }));
            }
            else
            {
                if ((bool)sender == true)
                {
                    lblState.Text = "在线";
                }
                else
                {
                    lblState.Text = "离线";
                }
            }
        }

        private void InitializeComponent()
        {
            this.btSerialSet = new System.Windows.Forms.Button();
            this.lblShow = new System.Windows.Forms.Label();
            this.lblState = new System.Windows.Forms.Label();
            this.btStartTest = new System.Windows.Forms.Button();
            this.btRead = new System.Windows.Forms.Button();
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // btSerialSet
            // 
            this.btSerialSet.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.btSerialSet.Location = new System.Drawing.Point(324, 86);
            this.btSerialSet.Name = "btSerialSet";
            this.btSerialSet.Size = new System.Drawing.Size(57, 40);
            this.btSerialSet.TabIndex = 0;
            this.btSerialSet.Text = "串口配置";
            this.btSerialSet.UseVisualStyleBackColor = true;
            this.btSerialSet.Click += new System.EventHandler(this.button1_Click);
            // 
            // lblShow
            // 
            this.lblShow.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
            this.lblShow.Font = new System.Drawing.Font("黑体", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.lblShow.ForeColor = System.Drawing.Color.Aqua;
            this.lblShow.Location = new System.Drawing.Point(3, 3);
            this.lblShow.Name = "lblShow";
            this.lblShow.Size = new System.Drawing.Size(378, 73);
            this.lblShow.TabIndex = 1;
            this.lblShow.Text = "----";
            this.lblShow.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // lblState
            // 
            this.lblState.BackColor = System.Drawing.Color.Red;
            this.lblState.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.lblState.Location = new System.Drawing.Point(18, 91);
            this.lblState.Name = "lblState";
            this.lblState.Size = new System.Drawing.Size(69, 23);
            this.lblState.TabIndex = 2;
            this.lblState.Text = "离线";
            this.lblState.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.lblState.TextChanged += new System.EventHandler(this.lblState_TextChanged);
            // 
            // btStartTest
            // 
            this.btStartTest.Location = new System.Drawing.Point(112, 79);
            this.btStartTest.Name = "btStartTest";
            this.btStartTest.Size = new System.Drawing.Size(64, 23);
            this.btStartTest.TabIndex = 3;
            this.btStartTest.Text = "Start";
            this.btStartTest.UseVisualStyleBackColor = true;
            this.btStartTest.Click += new System.EventHandler(this.btStartTest_Click);
            // 
            // btRead
            // 
            this.btRead.Location = new System.Drawing.Point(223, 85);
            this.btRead.Name = "btRead";
            this.btRead.Size = new System.Drawing.Size(64, 39);
            this.btRead.TabIndex = 4;
            this.btRead.Text = "Read";
            this.btRead.UseVisualStyleBackColor = true;
            this.btRead.Click += new System.EventHandler(this.btRead_Click);
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(112, 103);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(64, 23);
            this.button1.TabIndex = 5;
            this.button1.Text = "Stop";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click_1);
            // 
            // HIOKIResistor
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.btRead);
            this.Controls.Add(this.btStartTest);
            this.Controls.Add(this.lblState);
            this.Controls.Add(this.lblShow);
            this.Controls.Add(this.btSerialSet);
            this.Size = new System.Drawing.Size(384, 129);
            this.ResumeLayout(false);

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form form = new Form();
            form.AutoSize = true;
            form.Text = Resistorserial.Name;
            form.Controls.Add((Control)Resistorserial);
            form.ShowDialog();
        }


        internal override void Resistorserial_OnReceiveData(string obj)
        {

            base.Resistorserial_OnReceiveData(obj);



        }

        int GetTestResultCount = 0;
        public override SendBackResult GetTestResult()
        {
            GetTestResultCount++;
            string testValue = "";
            SendBackResult sendBackResult = base.GetTestResult();
            if (sendBackResult.Success)
            {
                string[] content = sendBackResult.Content.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < content.Length; i++)
                {
                    if (content[i].Contains("E+06"))
                    {
                        testValue = content[i].Replace("E+06", "");
                        break;
                    }
                }
                if (testValue != "")
                {
                    GetTestResultCount = 0;
                    if (this.InvokeRequired)
                    {
                        this.BeginInvoke(new Action(() =>
                        {
                            lblShow.Text = testValue;
                        }));
                    }
                    else
                    {
                        lblShow.Text = testValue;
                    }
                    return SendBackResult.CreateSuccess(testValue);
                }
                else
                {
                    if (GetTestResultCount <= 5)
                    {
                        return GetTestResult();
                    }
                    else
                    {
                        GetTestResultCount = 0;
                        return SendBackResult.CreateFailure(32211, $"返回的字符串中不包含有效信息，返回字符串为 {sendBackResult.Content}");
                    }
                }
            }
            else
            {
                if (this.InvokeRequired)
                {
                    this.BeginInvoke(new Action(() =>
                    {
                        lblShow.Text = sendBackResult.Content + sendBackResult.ErrMsg;
                    }));
                }
                else
                {
                    lblShow.Text = sendBackResult.Content + sendBackResult.ErrMsg;
                }
                return sendBackResult;
            }
        }

        private void lblState_TextChanged(object sender, EventArgs e)
        {
            if (lblState.Text == "离线")
            {
                lblState.BackColor = Color.Red;
            }
            else if (lblState.Text == "在线")
            {
                lblState.BackColor = Color.Lime;
            }
        }

        private void btStartTest_Click(object sender, EventArgs e)
        {
            SendBackResult sendBackResult = StartTest();
            if (sendBackResult.Success)
            {
                lblShow.Text = sendBackResult.Content;
            }
            else
            {
                lblShow.Text = sendBackResult.ErrMsg;
            }
        }

        private void btRead_Click(object sender, EventArgs e)
        {
            SendBackResult sendBackResult = GetTestResult();
            if (sendBackResult.Success)
            {
                lblShow.Text = sendBackResult.Content;
            }
            else
            {
                lblShow.Text = sendBackResult.ErrMsg;
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            SendBackResult sendBackResult = StopTest();
            if (sendBackResult.Success)
            {
                lblShow.Text = sendBackResult.Content;
            }
            else
            {
                lblShow.Text = sendBackResult.ErrMsg;
            }
        }



        public override SendBackResult StartTest()
        {
            if (ConnectionStatus)
            {
                Resistorserial.AllReceivedString = "";
                SendBackResult sendBackResult = Resistorserial.SendBackMessageInstant(StartTestSendCmd, TestMaxTime);
                if (sendBackResult.Success)
                {
                    //if (sendBackResult.Content != "OK\r\n")
                    //{
                    //    return SendBackResult.CreateFailure(98842, $"{Name}开始测试返回异常值{sendBackResult.Content}");
                    //}
                    //else
                    //{
                    return SendBackResult.CreateSuccess(sendBackResult.Content);
                    //}
                }
                else
                {
                    return sendBackResult;
                }
            }
            else
            {
                return SendBackResult.CreateFailure(933, $"{Name}通讯不在线");
            }
        }


        public override SendBackResult StopTest()
        {
            if (ConnectionStatus)
            {
                Resistorserial.SendMessage(StopTestSendCmd);
                //if (sendBackResult.Success)
                //{


                return SendBackResult.CreateSuccess("");

                //}
                //else
                //{
                //    return sendBackResult;
                //}
            }
            else
            {
                return SendBackResult.CreateFailure(933, $"{Name}通讯不在线");
            }
        }
    }
}
